/**
 * @typedef ad - 广告位信息
 * @property {integer} _id - 广告_id 添加不用_id
 * @property {string} name.required - Some description for product
 * @property {Array.<item>} items - 物品信息
 */

module.exports = () => {
  const express = require('express')
  const router = express.Router()
  /**
  * This function comment is parsed by doctrine
  * @route POST /ads
  * @group 广告位 - 增加广告位信息
  * @returns {model} 200 - 新增广告位信息
  * @returns {Error}  500 - 服务器出现错误
  */
  //增加    
  router.post('/', async (req, res) => {
    const model = await req.Model.create(req.body)
    res.send(model)
  })
  /**
  * This function comment is parsed by doctrine
  * @route GET /ads
  * @group 广告位 - 查找所有广告位信息
  * @returns {model} 200 - 所有广告位信息
  * @returns {Error}  500 - 服务器出现错误
  */
  //查找所有
  router.get('/', async (req, res) => {
    let queryOptions = {}
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent'
    }
    if (req.Model.modelName === 'Article') {
      queryOptions.populate = 'categories'
    }
    const items = await req.Model.find().setOptions(queryOptions)
    res.send(items)
  })
  /**
  * This function comment is parsed by doctrine
  * @route GET /ads/:id
  * @group 广告位 - 查找某个广告位信息
  * @param {string} id.params.required - 广告位_id
  * @returns {model} 200 - 单个广告位信息
  * @returns {Error}  500 - 服务器出现错误
  */
  //查找
  router.get('/:id', async (req, res) => {
    const model = await req.Model.findById(req.params.id)
    res.send(model)
  })
  /**
  * This function comment is parsed by doctrine
  * @route PUT /ads/:id
  * @group 广告位 - 编辑某个广告位信息
  * @param {string} id.params.required - 广告位_id
  * @returns {model} 200 - 单个广告位信息
  * @returns {Error}  500 - 服务器出现错误
  */
  //编辑
  router.put('/:id', async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send(model)
  })
  /**
  * This function comment is parsed by doctrine
  * @route DELETE /ads/:id
  * @group 广告位 - 删除某个广告位信息
  * @param {string} id.params.required - 广告位_id
  * @returns {model} 200 - 是否成功
  * @returns {Error}  500 - 服务器出现错误
  */
  //删除
  router.delete('/:id', async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id)
    res.send({
      success: true
    })
  })
}